package com.auntvt.timo.jpax.springbootstarter.helper;

import com.auntvt.timo.jpax.core.utils.SpringContextUtil;
import com.auntvt.timo.jpax.springbootstarter.config.properties.JpaxPageProperties;
import com.auntvt.timo.jpax.springbootstarter.utils.HttpServletUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * 分页排序助手
 *
 * @author 小懒虫
 * @date 2018/12/8
 */
public class PageHelper {

    /**
     * 默认显示条数值
     */
    public static final Integer PAGE_SIZE_DEF = 10;

    /**
     * 默认排序字段
     */
    public static final String ORDER_BY_COLUMN_DEF = "createDate";

    /**
     * 排序字段分隔符
     */
    public static final String ORDER_BY_COLUMN_SPLIT = ",";

    /**
     * 默认排序方式
     */
    public static final Sort.Direction SORT_DIRECTION = Sort.Direction.DESC;

    /**
     * 创建分页排序对象
     */
    public static PageRequest pageRequest() {
        return pageRequest(PAGE_SIZE_DEF, ORDER_BY_COLUMN_DEF, SORT_DIRECTION);
    }

    /**
     * 创建分页排序对象
     *
     * @param pageSizeDef 显示条数值
     */
    public static PageRequest pageRequest(Integer pageSizeDef) {
        return pageRequest(pageSizeDef, ORDER_BY_COLUMN_DEF, SORT_DIRECTION);
    }

    /**
     * 创建分页排序对象
     *
     * @param orderByColumnDef 排序字段名称
     */
    public static PageRequest pageRequest(String orderByColumnDef) {
        return pageRequest(PAGE_SIZE_DEF, orderByColumnDef, SORT_DIRECTION);
    }

    /**
     * 创建分页排序对象
     *
     * @param sortDirection 排序方式
     */
    public static PageRequest pageRequest(Sort.Direction sortDirection) {
        return pageRequest(PAGE_SIZE_DEF, ORDER_BY_COLUMN_DEF, sortDirection);
    }

    /**
     * 创建分页排序对象
     *
     * @param orderByColumnDef 排序字段名称
     * @param sortDirection    排序方式
     */
    public static PageRequest pageRequest(String orderByColumnDef, Sort.Direction sortDirection) {
        return pageRequest(PAGE_SIZE_DEF, orderByColumnDef, sortDirection);
    }

    /**
     * 创建分页排序对象
     *
     * @param pageSizeDef      显示条数值
     * @param orderByColumnDef 排序字段名称
     * @param sortDirection    排序方式
     */
    public static PageRequest pageRequest(Integer pageSizeDef, String orderByColumnDef, Sort.Direction sortDirection) {
        JpaxPageProperties properties = SpringContextUtil.getBean(JpaxPageProperties.class);
        Integer pageIndex = HttpServletUtil.getParameterInt(properties.getPage(), 1);
        Integer pageSize = HttpServletUtil.getParameterInt(properties.getSize(), pageSizeDef);
        String orderByColumns = HttpServletUtil.getParameter(properties.getOrderBy(), orderByColumnDef);
        String direction = HttpServletUtil.getParameter(properties.getDir(), sortDirection.toString());
        Sort sort = Sort.by(Sort.Direction.fromString(direction), orderByColumns.split(ORDER_BY_COLUMN_SPLIT));
        return PageRequest.of(pageIndex - 1, pageSize, sort);
    }
}
